package btree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BTree {

    public static void main(String[] args) {
        String inputStr = args[0].substring(1,args[0].length()-1);
        String[] inputStrArr = inputStr.split(",");
        Integer[] intArr = new Integer[inputStrArr.length];
        for(int i=0; i<inputStrArr.length; i++) {
            intArr[i] = Integer.parseInt(inputStrArr[i]);
        }
        BTree bTree = new BTree();
        TreeNode root = bTree.buildTree(intArr);
        TreeNode invertRoot = bTree.invertTree(root);
        List<Integer> layerPrint = bTree.layerPrint(invertRoot);
        System.out.println(layerPrint);
    }
    // 按层遍历二叉树
    public List<Integer> layerPrint(TreeNode root) {
        if (root == null) {
            return null;
        }
        List<Integer> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                result.add(node.val);

                // 左子树入队列
                queue.offer(node.left);
                // 右子树入队列
                queue.offer(node.right);
            }
            
        }
        return result;
    }

    // 翻转二叉树
    // 输入：root = [4,2,7,1,3,6,9]
    // 输出：[4,7,2,9,6,3,1]
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }

    // 数组转二叉树
    public TreeNode buildTree(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(arr[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int i = 1;
        while (!queue.isEmpty() && i<arr.length) {
            TreeNode curNode = queue.poll();

            if (i<arr.length && arr[i] != null) {
                TreeNode tmp = new TreeNode(arr[i]);
                curNode.left = tmp;
                queue.offer(tmp);
            }
            i++;
            if (i<arr.length && arr[i] != null) {
                TreeNode tmp = new TreeNode(arr[i]);
                curNode.right = tmp;
                queue.offer(tmp);
            }
            i++;
        }
        return root;
    }
    
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
